package com.zdkj.edge.door.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class AccessRecordStateManager {

  private static final String FILE_PATH = "last_access_record.json";
  private final Map<String, String> lastBrushTimeMap = new HashMap<>();

  public AccessRecordStateManager() {
    load();
  }

  public synchronized void updateLastBrushTime(String deviceKey, String time) {
    lastBrushTimeMap.put(deviceKey, time);
    save();
  }

  public synchronized String getLastBrushTime(String deviceKey) {
    return lastBrushTimeMap.getOrDefault(deviceKey, "1970-01-01 00:00:00");
  }

  private void save() {
    try {
      Files.write(Paths.get(FILE_PATH),
          JSON.toJSONString(lastBrushTimeMap, true).getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
      System.err.println("保存 lastBrushTimeMap 失败: " + e.getMessage());
    }
  }

  private void load() {
    try {
      File file = new File(FILE_PATH);
      if (file.exists()) {
        String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
        Map<String, String> map = JSON.parseObject(content, new TypeReference<Map<String, String>>() {});
        lastBrushTimeMap.putAll(map);
      }
    } catch (IOException e) {
      log.error("加载 lastBrushTimeMap 失败: " + e.getMessage());
    }
  }
}
